<template>
  <div class="customer-service-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="header-title">客服列表</span>
          <el-button type="primary" @click="handleAdd" class="add-button">
            <el-icon><Plus /></el-icon>新建客服
          </el-button>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-container">
        <el-input
          v-model="queryParams.nickname"
          placeholder="请输入昵称"
          clearable
          class="search-input"
          @keyup.enter="handleQuery"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <span class="search-tip">注意：微信客户在主动发送消息给客服后的48小时内，企业可发送消息给客户，最多可发送5条消息；若用户继续发送消息，企业可再次发送消息</span>
      </div>
      
      <!-- 客服列表 -->
      <div v-loading="loading" class="service-list">
        <div 
          v-for="item in serviceList" 
          :key="item.id" 
          class="service-item"
        >
          <div class="service-info">
            <el-avatar :src="item.avatar" :size="50" class="service-avatar">
              <span>{{ item.nickname.charAt(0) }}</span>
            </el-avatar>
            <div class="service-details">
              <h3 class="service-nickname">{{ item.nickname }} 
                 <el-button
                 type="primary"
                 link
                 @click="handleEdit(item)"
                 style="margin-left: 12px; padding-left: 0;"
               >
                 修改客服
               </el-button></h3>
              
              <p class="service-meta">ID: {{ item.id }} | 创建于: {{ item.created_at }}</p>
              <div class="auto-reply-switch">
                <span class="switch-label">关键词自动回复：</span>
                <el-switch
                  v-model="item.auto_reply_enabled"
                  active-text="开启"
                  inactive-text="关闭"
                  @change="handleAutoReplyChange(item)"
                />
              </div>
              <div class="auto-reply-switch">
                <span class="switch-label">自动回复：</span>
                <el-switch
                  v-model="item.is_open_auto_reply"
                  active-text="开启"
                  inactive-text="关闭"
                  @change="handleAutoReplyChange2(item)"
                />
              </div>

              <div class="auto-reply-switch" v-if="item.is_bind_wechat == 1">
                <span class="switch-label" style="font-weight: bold;color:#ff0000;">当前客服已关注公众号</span>
                
              </div>
            </div>
          </div>
          <div class="service-actions">
            <el-button
              type="primary"
              link
              @click="handleViewDetail(item)"
              :size="appStore.isMobile ? 'small' : 'default'"
            >
              会话详情
            </el-button>
            <el-button
              type="success"
              link
              @click="handleGetLink(item)"
              :size="appStore.isMobile ? 'small' : 'default'"
            >
              获取客服账号链接
            </el-button>
            <el-button
              type="info"
              link
              @click="handleGetWebLink(item)"
              :size="appStore.isMobile ? 'small' : 'default'"
              v-if="!appStore.isMobile"
            >
              获取客服外链
            </el-button>
            <el-button
              type="warning"
              link
              @click="handleSetWelcome(item)"
              :size="appStore.isMobile ? 'small' : 'default'"
            >
              欢迎语设置
            </el-button>
            <el-button
              type="info"
              link
              @click="handleKeywordReply(item)"
              :size="appStore.isMobile ? 'small' : 'default'"
              v-if="!appStore.isMobile"
            >
              关键词设置
            </el-button>
            <el-button
              type="primary"
              link
              @click="handleAutoReply(item)"
              :size="appStore.isMobile ? 'small' : 'default'"
              v-if="!appStore.isMobile"
            >
              自动回复设置
            </el-button>
            
            <!-- 移动端下拉菜单 -->
            <el-dropdown v-if="appStore.isMobile" trigger="click">
              <el-button type="info" link size="small">
                更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleGetWebLink(item)">
                    获取客服外链
                  </el-dropdown-item>
                  <el-dropdown-item @click="handleKeywordReply(item)">
                    关键词设置
                  </el-dropdown-item>
                  <el-dropdown-item @click="handleAutoReply(item)">
                    自动回复设置
                  </el-dropdown-item>
                  <el-dropdown-item v-if="item.is_bind_wechat == 0" @click="bindWechat(item)">
                    关注公众号
                  </el-dropdown-item>
                  <el-dropdown-item divided @click="handleDelete(item)">
                    <span style="color: #f56c6c">删除</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            
            <!-- 桌面端显示的按钮 -->
            <template v-if="!appStore.isMobile">
              <el-button
                type="success"
                link
                @click="bindWechat(item)"
                v-if="item.is_bind_wechat == 0"
              >
                关注公众号
              </el-button>
              <el-button
                type="danger"
                link
                @click="handleDelete(item)"
              >
                删除
              </el-button>
            </template>
          </div>
        </div>
        
        <!-- 空状态 -->
        <div v-if="!loading && serviceList.length === 0" class="empty-state">
          <el-empty description="暂无客服数据">
            <el-button type="primary" @click="handleAdd">新建客服</el-button>
          </el-empty>
        </div>
      </div>
      
      <!-- 分页区域 -->
      <div class="pagination-container" v-if="total > 0">
        <div class="pagination-info">
          共 {{ total }} 条
        </div>
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          small
        />
      </div>
    </el-card>
    
    <!-- 新增/编辑客服弹框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogMode === 'add' ? '新建客服' : '编辑客服'"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入机器人昵称" />
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <div class="avatar-upload-container">
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :auto-upload="false"
              :before-upload="beforeAvatarUpload"
              :on-change="handleAvatarChange"
            >
              <img v-if="form.avatar" :src="form.avatar" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="upload-actions" v-if="selectedFile">
              <!-- <el-button type="primary" size="small" @click="uploadSelectedAvatar" :loading="uploadLoading">
                上传头像
              </el-button> -->
              <el-button size="small" @click="cancelUpload">
                取消
              </el-button>
            </div>
          </div>
          <div class="avatar-tip">建议上传正方形图片，大小不超过2MB</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="uploadSelectedAvatar" :loading="submitLoading">
            {{ dialogMode === 'add' ? '确定' : '保存' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 欢迎语设置弹框 -->
    <el-dialog
      v-model="welcomeDialogVisible"
      title="设置欢迎语"
      width="600px"
      :close-on-click-modal="false"
      class="welcome-dialog"
    >
      <el-form
        ref="welcomeFormRef"
        :model="welcomeForm"
        :rules="welcomeRules"
        label-width="100px"
      >
        <el-form-item label="客服昵称">
          <el-input v-model="currentService.nickname" readonly />
        </el-form-item>
        <el-form-item label="欢迎语" prop="content">
          <el-input
            v-model="welcomeForm.content"
            type="textarea"
            :rows="5"
            placeholder="请输入欢迎语，用户进入聊天时会自动发送此消息"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item>
          <el-alert
            title="提示"
            type="info"
            show-icon
            :closable="false"
          >
            <template #default>
              <p>欢迎语将在用户首次进入聊天时自动发送</p>
             
            </template>
          </el-alert>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelWelcomeDialog">取消</el-button>
          <el-button type="primary" @click="saveWelcomeMessage" :loading="welcomeSubmitLoading">
            <el-icon><Check /></el-icon>
            保存设置
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 链接弹框 -->
    <el-dialog
      v-model="linkDialogVisible"
      title="生成链接"
      width="600px"
      align-center
    >
      <div class="link-container">
        <el-form ref="linkFormRef" :model="linkForm" :rules="linkRules" label-width="100px">
          <el-form-item label="链接类型" prop="type" required>
            <el-radio-group v-model="linkForm.type">
              <el-radio value="1">客服</el-radio>
              <el-radio value="2">广告</el-radio>
              <el-radio value="3">创意</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item v-if="linkForm.type == '2'" label="选择广告" prop="advertisement_id" required>
            <el-select v-model="linkForm.advertisement_id" placeholder="请选择广告" style="width: 100%" filterable>
              <el-option
                v-for="item in advertisementList"
                :key="item.id"
                :label="item.label"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item v-if="linkForm.type == '3'" label="选择创意" prop="creative_id" required>
            <el-select v-model="linkForm.creative_id" placeholder="请选择创意" style="width: 100%" filterable>
              <el-option
                v-for="item in creativeList"
                :key="item.id"
                :label="item.label"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
        
        <div class="link-actions">
          <el-button type="primary" @click="generateLink" :loading="generateLoading">
            生成链接
          </el-button>
        </div>
        
        <div v-if="serviceLink" class="link-result">
          <p class="link-tips">生成的链接地址：</p>
          <el-input
            v-model="serviceLink"
            readonly
            size="large"
            class="link-input"
          >
            <template #append>
              <el-button @click="copyLink" :loading="copyLoading">
                <el-icon><Document /></el-icon>复制
              </el-button>
            </template>
          </el-input>
          <div class="qr-code-container" v-if="serviceLink">
            <p>或扫描二维码</p>
            <div class="qr-code">
              <img :src="`https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=${encodeURIComponent(serviceLink)}`" alt="二维码" />
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 新增：关键词回复设置弹框 -->
    <el-dialog
      v-model="keywordDialogVisible"
      title="关键词回复设置"
      width="800px"
      :close-on-click-modal="false"
      class="keyword-dialog"
    >
      <div class="keyword-header">
        <div class="service-info-header">
          <el-avatar :src="currentService?.avatar" :size="40">
            <span>{{ currentService.nickname?.charAt(0) || '' }}</span>
          </el-avatar>
          <span class="service-name">{{ currentService.nickname || '' }}</span>
        </div>
        <el-button type="primary" @click="handleAddKeyword">
          <el-icon><Plus /></el-icon>
          新增关键词
        </el-button>
      </div>

      <!-- 关键词列表 -->
      <div class="keyword-content">
        <el-table :data="keywordList" style="width: 100%" max-height="400">
          <el-table-column prop="keywords" label="关键词" width="150" />
          <el-table-column prop="type" label="回复类型" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.type === 1 ? 'primary' : 'success'">
                {{ scope.row.type === 1 ? '文字' : '图片' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="content" label="回复内容" min-width="200">
            <template #default="scope">
              <div v-if="scope.row.type === 1" class="text-content">
                {{ scope.row.content }}
              </div>
              <div v-else class="image-content">
                <el-image
                  :src="scope.row.content"
                  fit="cover"
                  style="width: 60px; height: 60px; border-radius: 4px;"
                  :preview-src-list="[scope.row.content]"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              
              <el-button
                type="danger"
                link
                @click="handleDeleteKeyword(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 空状态 -->
        <div v-if="keywordList.length === 0" class="keyword-empty">
          <el-empty description="暂无关键词回复配置">
            <el-button type="primary" @click="handleAddKeyword">
              <el-icon><Plus /></el-icon>
              新增关键词
            </el-button>
          </el-empty>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="keywordDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增/编辑关键词弹框 -->
    <el-dialog
      v-model="keywordFormDialogVisible"
      :title="keywordFormMode === 'add' ? '新增关键词' : '编辑关键词'"
      width="500px"
      :close-on-click-modal="false"
      class="keyword-form-dialog"
    >
      <el-form
        ref="keywordFormRef"
        :model="keywordForm"
        :rules="keywordRules"
        label-width="100px"
      >
        <el-form-item label="关键词" prop="keyword">
          <el-input 
            v-model="keywordForm.keyword" 
            placeholder="请输入关键词"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="回复类型" prop="type">
          <el-radio-group v-model="keywordForm.type">
            <el-radio value="text">文字回复</el-radio>
            <el-radio value="image">图片回复</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="keywordForm.type === 'text'" label="回复内容" prop="content">
          <el-input
            v-model="keywordForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入回复内容"
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>
        <el-form-item v-if="keywordForm.type === 'image'" label="回复图片" prop="content">
          <div class="image-upload-container">
            <el-upload
              class="image-uploader"
              :show-file-list="false"
              :auto-upload="false"
              :before-upload="beforeImageUpload"
              :on-change="handleImageChange"
            >
              <img v-if="keywordForm.content" :src="keywordForm.content" class="uploaded-image" />
              <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="image-tip">建议上传图片，大小不超过5MB</div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="keywordFormDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveKeyword" :loading="keywordSubmitLoading">
            {{ keywordFormMode === 'add' ? '新增' : '保存' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 自动回复设置弹框 -->
    <el-dialog
      v-model="autoReplyDialogVisible"
      title="自动回复设置"
      width="800px"
      :close-on-click-modal="false"
      class="auto-reply-dialog"
    >
      <div class="auto-reply-header">
        <div class="service-info-header">
          <el-avatar :src="currentService?.avatar" :size="40">
            <span>{{ currentService.nickname?.charAt(0) || '' }}</span>
          </el-avatar>
          <span class="service-name">{{ currentService.nickname || '' }}</span>
        </div>
        <el-button type="primary" @click="handleAddAutoReply">
          <el-icon><Plus /></el-icon>
          新增自动回复
        </el-button>
      </div>

      <!-- 自动回复列表 -->
      <div class="auto-reply-content">
        <el-table :data="autoReplyList" style="width: 100%" max-height="400">
          <el-table-column prop="type" label="回复类型" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.type === 1 ? 'primary' : 'success'">
                {{ scope.row.type === 1 ? '文字' : '图片' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="content" label="回复内容" min-width="200">
            <template #default="scope">
              <div v-if="scope.row.type === 1" class="text-content">
                {{ scope.row.content }}
              </div>
              <div v-else class="image-content">
                <el-image
                  :src="scope.row.content"
                  fit="cover"
                  style="width: 60px; height: 60px; border-radius: 4px;"
                  :preview-src-list="[scope.row.content]"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button
                type="danger"
                link
                @click="handleDeleteAutoReply(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 空状态 -->
        <div v-if="autoReplyList.length === 0" class="auto-reply-empty">
          <el-empty description="暂无自动回复配置">
            <el-button type="primary" @click="handleAddAutoReply">
              <el-icon><Plus /></el-icon>
              新增自动回复
            </el-button>
          </el-empty>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="autoReplyDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增/编辑自动回复弹框 -->
    <el-dialog
      v-model="autoReplyFormDialogVisible"
      :title="autoReplyFormMode === 'add' ? '新增自动回复' : '编辑自动回复'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form ref="autoReplyFormRef" :model="autoReplyForm" :rules="autoReplyRules" label-width="80px">
        <el-form-item label="回复类型" prop="type">
          <el-radio-group v-model="autoReplyForm.type">
            <el-radio :label="1">文字</el-radio>
            <el-radio :label="2">图片</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="autoReplyForm.type === 1" label="回复内容" prop="content">
          <el-input
            v-model="autoReplyForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入自动回复的文字内容"
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>
        <el-form-item v-if="autoReplyForm.type === 2" label="选择图片" prop="content">
          <div class="image-upload-container">
            <el-upload
              class="avatar-uploader"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleImageSelect"
              accept="image/*"
            >
              <div v-if="autoReplyForm.content || selectedImageFile" class="image-preview">
                <img 
                  :src="selectedImageFile ? getFilePreviewUrl(selectedImageFile) : autoReplyForm.content" 
                  alt="预览图片"
                  class="uploaded-image"
                />
                <div class="image-overlay">
                  <el-button type="primary" size="small">重新选择</el-button>
                </div>
              </div>
              <div v-else class="upload-placeholder">
                <el-icon class="upload-icon"><Plus /></el-icon>
                <div class="upload-text">点击选择图片</div>
              </div>
            </el-upload>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="autoReplyFormDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveAutoReply" :loading="autoReplySubmitLoading">
            {{ autoReplyFormMode === 'add' ? '新增' : '保存' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 公众号二维码弹框 -->
    <el-dialog
      v-model="qrcodeDialogVisible"
      title="微信公众号二维码"
      width="400px"
      :close-on-click-modal="false"
      center
    >
      <div class="qrcode-container">
        <div v-if="qrcodeLoading" class="qrcode-loading">
          <el-icon class="is-loading"><Loading /></el-icon>
          <p>正在生成二维码...</p>
        </div>
        <div v-else-if="qrcodeUrl" class="qrcode-content">
          <div class="qrcode-image">
            <img :src="qrcodeUrl" alt="公众号二维码" />
          </div>
          <div class="qrcode-tips">
            <el-icon><InfoFilled /></el-icon>
            <p>请使用微信扫描上方二维码关注公众号</p>
            <p class="refresh-tip">扫码关注后，请刷新页面查看结果</p>
          </div>
        </div>
        <div v-else class="qrcode-error">
          <el-icon><WarningFilled /></el-icon>
          <p>二维码获取失败，请重试</p>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="qrcodeDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="refreshPage">刷新页面</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Search, Refresh, Plus, Document, Check, InfoFilled, WarningFilled, Loading, ArrowDown } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormRules, FormInstance, UploadProps, UploadRequestOptions } from 'element-plus'
import { useRouter } from 'vue-router'
import { getKefuWxgzh,getServicerList,getKefuWebLink,getCustomerServiceList, addCustomerService, editCustomerService, uploadServiceAvatar, getCustomerServiceLink, setWelcomeMessage, getWelcomeMessage, setAutoReplyStatus, getKeywordReplyList, addKeywordReply, updateKeywordReply, deleteKeywordReply, uploadKeywordImage, deleteCustomerService, getAutoReplyList, addAutoReply, updateAutoReply, deleteAutoReply, uploadAutoReplyImage, getAdvertisementList, getCreativeList, generateServiceLink,setAutoReplyStatus2 } from '@/api/customer-service'
import useAppStore from '@/stores/modules/app'

// 接口类型定义
interface CustomerService {
  id: string | number
  nickname: string
  avatar: string
  created_at: string
  auto_reply_enabled: boolean
  is_open_auto_reply: boolean
  is_bind_wechat: number
  open_kfid?: string
}

interface KeywordReply {
  id?: string | number
  keyword: string
  type: 'text' | 'image'
  content: string
}

interface AutoReply {
  id?: string | number
  type: 1 | 2
  content: string
}

const router = useRouter()
const appStore = useAppStore()

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  nickname: ''
})

const loading = ref(false)
const total = ref(0)
const serviceList = ref<CustomerService[]>([])

// 弹框相关
const dialogVisible = ref(false)
const dialogMode = ref<'add' | 'edit'>('add')
const formRef = ref<FormInstance>()
const submitLoading = ref(false)

// 文件上传相关
const selectedFile = ref<File | null>(null)
const uploadLoading = ref(false)

// 表单数据
const form = reactive({
  id: undefined as string | number | undefined,
  nickname: '',
  avatar: '',
  avatarFile: null as File | null,
  open_kfid: ''
})

// 表单校验规则
const rules = reactive<FormRules>({
  nickname: [
    { required: true, message: '请输入机器人昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  avatar: [
    { required: true, message: '请上传机器人头像', trigger: 'change' }
  ]
})

// 自动回复相关
const autoReplyDialogVisible = ref(false)
const autoReplyFormDialogVisible = ref(false)
const autoReplyFormMode = ref<'add' | 'edit'>('add')
const autoReplyFormRef = ref<FormInstance>()
const autoReplySubmitLoading = ref(false)
const autoReplyForm = reactive({
  type: 1 as 1 | 2,
  content: '',
  id: undefined as string | number | undefined
})
const autoReplyRules = reactive<FormRules>({
  type: [
    { required: true, message: '请选择回复类型', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入回复内容', trigger: 'blur' },
    { max: 1000, message: '回复内容长度不能超过1000个字符', trigger: 'blur' }
  ]
})
const autoReplyList = ref<AutoReply[]>([])

// 链接弹框相关
const linkDialogVisible = ref(false)
const linkFormRef = ref<FormInstance>()
const serviceLink = ref('')
const copyLoading = ref(false)
const generateLoading = ref(false)

// 链接表单数据
const linkForm = reactive({
  type: '1',
  advertisement_id: '',
  creative_id: ''
})

// 链接表单验证规则
const linkRules = reactive<FormRules>({
  type: [
    { required: true, message: '请选择链接类型', trigger: 'change' }
  ],
  advertisement_id: [
    { required: true, message: '请选择广告', trigger: 'change' }
  ],
  creative_id: [
    { required: true, message: '请选择创意', trigger: 'change' }
  ]
})

// 广告列表和创意列表
const advertisementList = ref<any[]>([])
const creativeList = ref<any[]>([])

// 查询数据
const getList = async () => {
  loading.value = true
  try {
    const response = await getCustomerServiceList({
      page_no: queryParams.pageNum,
      page_size: queryParams.pageSize,
      nickname: queryParams.nickname || undefined
    })

    console.log(response);
    
    serviceList.value = response.list || []
    total.value = response.count || 0
  } catch (error) {
    console.error('获取客服列表失败', error)
    ElMessage.error('获取客服列表失败')
    // 使用模拟数据，实际项目中可以删除以下代码
    serviceList.value = [
      
    ]
    total.value = serviceList.value.length
  } finally {
    loading.value = false
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryParams.pageNum = 1
  queryParams.nickname = ''
  getList()
}

// 分页大小变化
const handleSizeChange = (val: number) => {
  queryParams.pageSize = val
  getList()
}

// 页码变化
const handleCurrentChange = (val: number) => {
  queryParams.pageNum = val
  getList()
}

// 查看会话详情
const handleViewDetail = (row: CustomerService) => {
  router.push({
    path: '/customer-service/detail',
    query: { id: row.id as string }
  })
}

// 新增客服
const handleAdd = () => {
  dialogMode.value = 'add'
  // 重置表单
  form.id = undefined
  form.nickname = ''
  form.avatar = ''
  form.avatarFile = null
  form.open_kfid = ''
  selectedFile.value = null
  // 显示弹框
  dialogVisible.value = true
}

// 编辑客服
const handleEdit = (row: CustomerService) => {
  dialogMode.value = 'edit'
  // 填充表单数据
  form.id = row.id
  form.nickname = row.nickname
  form.avatar = row.avatar
  form.avatarFile = null
  form.open_kfid = row.open_kfid || ''
  selectedFile.value = null
  // 显示弹框
  dialogVisible.value = true
  console.log('编辑客服，头像URL:', row.avatar)
}

// 上传头像前的校验
const beforeAvatarUpload: UploadProps['beforeUpload'] = (file) => {
  // 检查文件类型
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('头像必须是图片格式')
    return false
  }
  
  // 检查文件大小（2MB）
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB')
    return false
  }
  
  return true
}

// 处理头像选择
const handleAvatarChange = (file: any) => {
  // 保存选择的文件
  selectedFile.value = file.raw
  
  // 创建临时预览URL
  form.avatar = URL.createObjectURL(file.raw)
}

// 上传头像并提交表单
const uploadSelectedAvatar = async () => {
  if (!formRef.value) return
  
  // 表单验证
  const valid = await formRef.value.validate().catch(() => false)
  if (!valid) {
    return
  }
  
  // 检查是否选择了头像
  if (!selectedFile.value && !form.avatarFile && !form.avatar) {
    ElMessage.error('请选择头像')
    return
  }
  
  submitLoading.value = true
  
  try {
    let avatarFile = form.avatarFile
    
    // 如果有新选择的文件，先上传头像
    if (selectedFile.value) {
      if (dialogMode.value === 'add') {
        // 新增客服时上传头像
        const uploadResponse = await uploadServiceAvatar(selectedFile.value, form.nickname)
        if (!uploadResponse || !uploadResponse.code) {
          ElMessage.error('添加客服失败')
          return
        }
        ElMessage.success('添加客服成功')
        dialogVisible.value = false
        getList()
        return
      } else {
        // 编辑客服时，直接调用编辑接口
        const response = await editCustomerService(
          selectedFile.value,
          form.nickname,
          form.open_kfid || undefined
        )
        
        if (response && response.code === 1) {
          ElMessage.success('编辑客服成功')
          dialogVisible.value = false
          getList()
        } else {
          ElMessage.error(response?.msg || '编辑客服失败')
        }
        return
      }
    }
    
    // 如果没有新文件，直接提交表单
    if (dialogMode.value === 'add') {
      // 新增客服
      const response = await addCustomerService({
        nickname: form.nickname,
        avatar: avatarFile as File
      })
      
      if (response && response.code === 1) {
        ElMessage.success('添加客服成功')
        dialogVisible.value = false
        getList()
      } else {
        ElMessage.error(response?.msg || '添加客服失败')
      }
    } else {
      // 编辑客服 - 需要将当前头像转换为File对象
      let avatarFileForEdit: File
      
      if (selectedFile.value) {
        // 如果选择了新文件，使用新文件
        avatarFileForEdit = selectedFile.value
      } else {
        // 如果没有选择新文件，将当前头像URL转换为File对象
        try {
          const response = await fetch(form.avatar)
          const blob = await response.blob()
          avatarFileForEdit = new File([blob], 'avatar.jpg', { type: blob.type })
        } catch (error) {
          console.error('转换头像失败', error)
          ElMessage.error('头像处理失败')
          return
        }
      }
      
      const response = await editCustomerService(
        avatarFileForEdit,
        form.nickname,
        form.open_kfid || undefined
      )
      
      if (response && response.code === 1) {
        ElMessage.success('编辑客服成功')
        dialogVisible.value = false
        getList()
      } else {
        ElMessage.error(response?.msg || '编辑客服失败')
      }
    }
  } catch (error) {
    console.error('操作失败', error)
    ElMessage.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

// 取消上传
const cancelUpload = () => {
  selectedFile.value = null
  form.avatar = ''
}

// 获取客服链接
const handleGetLink = async (row: CustomerService) => {
  currentService.value = row
  linkDialogVisible.value = true
  serviceLink.value = ''
  
  // 重置表单
  linkForm.type = '1'
  linkForm.advertisement_id = ''
  linkForm.creative_id = ''
  
  // 加载广告和创意列表
  await Promise.all([
    loadAdvertisementList(),
    loadCreativeList()
  ])
}

// 获取客服外链
const handleGetWebLink = async (row: CustomerService) => {
  try {
    const response = await getKefuWebLink({kefu_id:row.id})
    if (response && response.url) {

      navigator.clipboard.writeText(response.url);
      ElMessage.success('外链复制成功，请在浏览器打开');
      
      //advertisementList.value = response.list
    }
  } catch (error) {
    console.error('获取客服外链失败', error)
  }
}

// 加载广告列表
const loadAdvertisementList = async () => {
  try {
    const response = await getAdvertisementList()
    if (response && response.list) {
      advertisementList.value = response.list
    }
  } catch (error) {
    console.error('获取广告列表失败', error)
  }
}

// 加载创意列表
const loadCreativeList = async () => {
  try {
    const response = await getCreativeList()
    if (response && response.list) {
      creativeList.value = response.list
    }
  } catch (error) {
    console.error('获取创意列表失败', error)
  }
}




// 生成链接
const generateLink = async () => {
  if (!linkFormRef.value || !currentService.value) return
  
  // 表单验证
  const valid = await linkFormRef.value.validate().catch(() => false)
  if (!valid) {
    return
  }
  
  generateLoading.value = true
  
  try {
    const params = {
      kefu_id: currentService.value.id,
      type: linkForm.type,
      ad_id: linkForm.advertisement_id || undefined,
      creative_id: linkForm.creative_id || undefined
    }
    
    const response = await generateServiceLink(params)
    if (response && response.url) {
      serviceLink.value = response.url
    } else {
      ElMessage.error('生成链接失败')
    }
  } catch (error) {
    console.error('生成链接失败', error)
    ElMessage.error('生成链接失败')
  } finally {
    generateLoading.value = false
  }
}

// 复制链接
const copyLink = () => {
  if (!serviceLink.value) {
    ElMessage.warning('链接为空')
    return
  }
  
  copyLoading.value = true
  
  try {
    // 创建一个临时textarea元素
    const textarea = document.createElement('textarea')
    textarea.value = serviceLink.value
    // 确保元素不可见
    textarea.style.position = 'absolute'
    textarea.style.left = '-9999px'
    document.body.appendChild(textarea)
    // 选中并复制
    textarea.select()
    document.execCommand('copy')
    // 移除临时元素
    document.body.removeChild(textarea)
    
    ElMessage.success('链接已复制到剪贴板')
  } catch (error) {
    console.error('复制链接失败', error)
    ElMessage.error('复制链接失败')
  } finally {
    copyLoading.value = false
  }
}

// 欢迎语设置相关
const welcomeDialogVisible = ref(false)
const welcomeFormRef = ref<FormInstance>()
const welcomeSubmitLoading = ref(false)
const welcomeForm = reactive({
  content: '',
  enabled: true
})
const currentService = ref<CustomerService | null>(null)
const welcomeRules = reactive<FormRules>({
  content: [
    { required: true, message: '请输入欢迎语', trigger: 'blur' },
    { max: 500, message: '欢迎语长度不能超过500个字符', trigger: 'blur' }
  ],
  enabled: [
    { required: true, message: '请选择启用状态', trigger: 'change' }
  ]
})

// 设置欢迎语
const handleSetWelcome = async (row: CustomerService) => {
  currentService.value = row
  
  // 获取当前欢迎语设置
  try {
    const response = await getWelcomeMessage(row.id)
    console.log('欢迎语详情：',response);
    if (response && response.welcome_text) {
      welcomeForm.content = response.welcome_text || ''
    } else {
      // 重置表单
      welcomeForm.content = ''
      welcomeForm.enabled = true
    }
  } catch (error) {
    console.error('获取欢迎语失败', error)
    // 重置表单
    welcomeForm.content = ''
    welcomeForm.enabled = true
  }
  
  welcomeDialogVisible.value = true
}

// 保存欢迎语
const saveWelcomeMessage = async () => {
  if (!welcomeFormRef.value || !currentService.value) return
  
  // 表单验证
  const valid = await welcomeFormRef.value.validate().catch(() => false)
  if (!valid) {
    return
  }
  
  welcomeSubmitLoading.value = true
  
  try {
    const response = await setWelcomeMessage({
      kefu_id: currentService.value.id,
      welcome_text: welcomeForm.content
    })

    if (response && response.code === 1) {
      ElMessage.success('欢迎语设置成功')
      welcomeDialogVisible.value = false
      // 重置表单
      welcomeForm.content = ''
      welcomeForm.enabled = true
    } else {
      ElMessage.error(response?.msg || '设置欢迎语失败')
    }
  } catch (error) {
    console.error('设置欢迎语失败', error)
    ElMessage.error('设置欢迎语失败')
  } finally {
    welcomeSubmitLoading.value = false
  }
}

// 取消欢迎语设置弹框
const cancelWelcomeDialog = () => {
  welcomeDialogVisible.value = false
}

// 关键词回复相关
const keywordDialogVisible = ref(false)
const keywordFormDialogVisible = ref(false)
const keywordFormMode = ref<'add' | 'edit'>('add')
const keywordFormRef = ref<FormInstance>()
const keywordSubmitLoading = ref(false)
const keywordForm = reactive({
  keyword: '',
  type: 'text',
  content: '',
  id: undefined as string | number | undefined
})
const keywordRules = reactive<FormRules>({
  keyword: [
    { required: true, message: '请输入关键词', trigger: 'blur' },
    { min: 1, max: 50, message: '关键词长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择回复类型', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入回复内容', trigger: 'blur' },
    { max: 1000, message: '回复内容长度不能超过1000个字符', trigger: 'blur' }
  ]
})
const keywordList = ref<KeywordReply[]>([])

// 新增关键词
const handleAddKeyword = () => {
  keywordFormMode.value = 'add'
  resetKeywordForm()
  keywordFormDialogVisible.value = true
}

// 编辑关键词
const handleEditKeyword = (row: KeywordReply) => {
  keywordFormMode.value = 'edit'
  keywordForm.keyword = row.keyword
  keywordForm.type = row.type
  keywordForm.content = row.content
  keywordForm.id = row.id
  keywordFormDialogVisible.value = true
}

// 删除关键词
const handleDeleteKeyword = async (row: KeywordReply) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个关键词回复吗？',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const response = await deleteKeywordReply(row.id!)
    if (response && response.code === 1) {
      ElMessage.success('删除成功')
      // 重新加载列表
      if (currentService.value) {
        await loadKeywordList(currentService.value.id)
      }
    } else {
      ElMessage.error(response?.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除关键词失败', error)
      ElMessage.error('删除关键词失败')
    }
  }
}

// 保存关键词
const saveKeyword = async () => {
  if (!keywordFormRef.value || !currentService.value) return
  
  // 表单验证
  const valid = await keywordFormRef.value.validate().catch(() => false)
  if (!valid) {
    return
  }
  
  keywordSubmitLoading.value = true
  
  try {
    let content = keywordForm.content
    
    // 如果是图片类型且选择了新文件，先上传图片
    if (keywordForm.type === 'image' && selectedImageFile.value) {
      const uploadResponse = await uploadKeywordImage(selectedImageFile.value, currentService.value.id,keywordForm.keyword,2)
      if (uploadResponse && uploadResponse.code === 1) {
        content = uploadResponse.url;

        ElMessage.success(`${keywordFormMode.value === 'add' ? '新增' : '编辑'}成功`)
      keywordFormDialogVisible.value = false
      // 重新加载列表
      await loadKeywordList(currentService.value.id)
      // 重置表单
      resetKeywordForm()

      } else {
        ElMessage.error('图片上传失败')
        return
      }

      return;
    }

    console.log('keyType',keywordForm.type);

    var keyType = 2;
    if(keywordForm.type === 'text'){
      keyType = 1;
    }

    
    const params = {
      kefu_id: currentService.value.id,
      keywords: keywordForm.keyword,
      type: keyType as 1 | 2,
      content
    }
    
    let response
    if (keywordFormMode.value === 'add') {
      response = await addKeywordReply(params)
    } else {
      response = await updateKeywordReply({
        id: keywordForm.id!,
        kefu_id: currentService.value.id,
        keyword: keywordForm.keyword,
        type: keywordForm.type as 'text' | 'image',
        content
      })
    }
    
    if (response && response.code === 1) {
      ElMessage.success(`${keywordFormMode.value === 'add' ? '新增' : '编辑'}成功`)
      keywordFormDialogVisible.value = false
      // 重新加载列表
      await loadKeywordList(currentService.value.id)
      // 重置表单
      resetKeywordForm()
    } else {
      ElMessage.error(response?.msg || `${keywordFormMode.value === 'add' ? '新增' : '编辑'}失败`)
    }
  } catch (error) {
    console.error('保存关键词失败', error)
    ElMessage.error('保存关键词失败')
  } finally {
    keywordSubmitLoading.value = false
  }
}

// 重置关键词表单
const resetKeywordForm = () => {
  keywordForm.keyword = ''
  keywordForm.type = 'text'
  keywordForm.content = ''
  keywordForm.id = undefined
  selectedImageFile.value = null
}

// 图片文件选择
const selectedImageFile = ref<File | null>(null)

// 处理图片选择
const handleImageChange = (file: any) => {
  selectedImageFile.value = file.raw
  // 创建临时预览URL
  if (keywordFormDialogVisible.value) {
    keywordForm.content = URL.createObjectURL(file.raw)
  } else if (autoReplyFormDialogVisible.value) {
    autoReplyForm.content = URL.createObjectURL(file.raw)
  }
}

// 处理图片选择（自动回复）
const handleImageSelect = (file: any) => {
  selectedImageFile.value = file.raw
  autoReplyForm.content = URL.createObjectURL(file.raw)
}

// 获取文件预览URL
const getFilePreviewUrl = (file: File) => {
  return URL.createObjectURL(file)
}

// 上传图片前的校验
const beforeImageUpload: UploadProps['beforeUpload'] = (file) => {
  // 检查文件类型
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('必须是图片格式')
    return false
  }
  
  // 检查文件大小（5MB）
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB')
    return false
  }
  
  return true
}

// 关键词回复
const handleKeywordReply = async (row: CustomerService) => {
  currentService.value = row
  keywordDialogVisible.value = true
  
  // 加载关键词列表
  await loadKeywordList(row.id)
}

// 加载关键词列表
const loadKeywordList = async (kefuId: string | number) => {
  try {
    const response = await getKeywordReplyList(kefuId)
    if (response && response.list) {
      keywordList.value = response.list
    } else {
      keywordList.value = []
    }
  } catch (error) {
    console.error('获取关键词列表失败', error)
    ElMessage.error('获取关键词列表失败')
    keywordList.value = []
  }
}

// 自动回复
const handleAutoReply = async (row: CustomerService) => {
  currentService.value = row
  autoReplyDialogVisible.value = true
  
  // 加载自动回复列表
  await loadAutoReplyList(row.id)
}

//绑定公众号
const bindWechat = async (row: CustomerService) => {
  currentService.value = row
  qrcodeDialogVisible.value = true
  qrcodeUrl.value = ''
  
  // 生成二维码
  await generateQRCode()
}

// 加载自动回复列表
const loadAutoReplyList = async (kefuId: string | number) => {
  try {
    const response = await getAutoReplyList(kefuId)
    if (response && response.list) {
      autoReplyList.value = response.list
    } else {
      autoReplyList.value = []
    }
  } catch (error) {
    console.error('获取自动回复列表失败', error)
    ElMessage.error('获取自动回复列表失败')
    autoReplyList.value = []
  }
}

// 自动回复
const handleAutoReplyChange = async (row: CustomerService) => {
  try {
    const response = await setAutoReplyStatus({
      kefu_id: row.id,
      is_open_keywords: row.auto_reply_enabled
    })
    
    if (response && response.code === 1) {
      ElMessage.success(`已${row.auto_reply_enabled ? '开启' : '关闭'}自动回复`)
    } else {
      // 回滚状态
      row.auto_reply_enabled = !row.auto_reply_enabled
      ElMessage.error(response?.msg || '设置失败')
    }
  } catch (error) {
    console.error('设置自动回复失败', error)
    // 回滚状态
    row.auto_reply_enabled = !row.auto_reply_enabled
    ElMessage.error('设置自动回复失败')
  }
}


const handleAutoReplyChange2 = async (row: CustomerService) => {
  try {
    const response = await setAutoReplyStatus2({
      kefu_id: row.id,
      is_open_auto_reply: row.is_open_auto_reply
    })
    
    if (response && response.code === 1) {
      ElMessage.success(`已${row.is_open_auto_reply ? '开启' : '关闭'}自动回复`)
    } else {
      // 回滚状态
      row.is_open_auto_reply = !row.is_open_auto_reply
      ElMessage.error(response?.msg || '设置失败')
    }
  } catch (error) {
    console.error('设置自动回复失败', error)
    // 回滚状态
    row.is_open_auto_reply = !row.is_open_auto_reply
    ElMessage.error('设置自动回复失败')
  }
}

// 删除客服
const handleDelete = async (row: CustomerService) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除客服"${row.nickname}"吗？删除后将无法恢复！`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: false
      }
    )
    
    const response = await deleteCustomerService(row.id)
    if (response && response.code === 1) {
      ElMessage.success('删除客服成功')
      // 重新加载列表
      await getList()
    } else {
      ElMessage.error(response?.msg || '删除客服失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除客服失败', error)
      ElMessage.error('删除客服失败')
    }
  }
}

// 新增自动回复
const handleAddAutoReply = () => {
  autoReplyFormMode.value = 'add'
  resetAutoReplyForm()
  autoReplyFormDialogVisible.value = true
}

// 编辑自动回复
const handleEditAutoReply = (row: AutoReply) => {
  autoReplyFormMode.value = 'edit'
  autoReplyForm.type = row.type
  autoReplyForm.content = row.content
  autoReplyForm.id = row.id
  autoReplyFormDialogVisible.value = true
}

// 删除自动回复
const handleDeleteAutoReply = async (row: AutoReply) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个自动回复吗？',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const response = await deleteAutoReply(row.id!)
    if (response && response.code === 1) {
      ElMessage.success('删除成功')
      // 重新加载列表
      if (currentService.value) {
        await loadAutoReplyList(currentService.value.id)
      }
    } else {
      ElMessage.error(response?.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除自动回复失败', error)
      ElMessage.error('删除自动回复失败')
    }
  }
}

// 保存自动回复
const saveAutoReply = async () => {
  if (!autoReplyFormRef.value || !currentService.value) return
  
  // 表单验证
  const valid = await autoReplyFormRef.value.validate().catch(() => false)
  if (!valid) {
    return
  }
  
  autoReplySubmitLoading.value = true
  
  try {
    let content = autoReplyForm.content
    
    // 如果是图片类型且选择了新文件，先上传图片
    if (autoReplyForm.type === 2 && selectedImageFile.value) {
      const uploadResponse = await uploadAutoReplyImage(selectedImageFile.value, currentService.value.id,2)
      if (uploadResponse && uploadResponse.code === 1) {
        ElMessage.success(`添加成功`)
        content = uploadResponse.url
        autoReplyFormDialogVisible.value = false
      // 重新加载列表
      await loadAutoReplyList(currentService.value.id)
      // 重置表单
      resetAutoReplyForm()
      } else {
        ElMessage.error('图片上传失败')
        return
      }

      return;
    }
    
    const params = {
      kefu_id: currentService.value.id,
      type: autoReplyForm.type as 1 | 2,
      content
    }
    
    let response
    if (autoReplyFormMode.value === 'add') {
      response = await addAutoReply(params)
    } else {
      response = await updateAutoReply({
        id: autoReplyForm.id!,
        kefu_id: currentService.value.id,
        type: autoReplyForm.type as 1 | 2,
        content
      })
    }
    
    if (response && response.code === 1) {
      ElMessage.success(`${autoReplyFormMode.value === 'add' ? '新增' : '编辑'}成功`)
      autoReplyFormDialogVisible.value = false
      // 重新加载列表
      await loadAutoReplyList(currentService.value.id)
      // 重置表单
      resetAutoReplyForm()
    } else {
      ElMessage.error(response?.msg || `${autoReplyFormMode.value === 'add' ? '新增' : '编辑'}失败`)
    }
  } catch (error) {
    console.error('保存自动回复失败', error)
    ElMessage.error('保存自动回复失败')
  } finally {
    autoReplySubmitLoading.value = false
  }
}

// 重置自动回复表单
const resetAutoReplyForm = () => {
  autoReplyForm.type = 1
  autoReplyForm.content = ''
  autoReplyForm.id = undefined
  selectedImageFile.value = null
}

// 公众号二维码弹框相关
const qrcodeDialogVisible = ref(false)
const qrcodeLoading = ref(false)
const qrcodeUrl = ref('')

// 生成二维码
const generateQRCode = async () => {
  qrcodeLoading.value = true
  try {
    const response = await getKefuWxgzh(currentService.value!.id)
    if (response && response.url) {
      qrcodeUrl.value = response.url
    } else {
      ElMessage.error('获取二维码失败')
    }
  } catch (error) {
    console.error('生成二维码失败', error)
    ElMessage.error('生成二维码失败')
  } finally {
    qrcodeLoading.value = false
  }
}

// 刷新页面
const refreshPage = () => {
  location.reload()
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.customer-service-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.add-button {
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 500;
}

.search-container {
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
  max-width: 100%;
}

.search-input :deep(.el-input__wrapper) {
  border-radius: 20px;
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  transition: all 0.3s;
}

.search-input :deep(.el-input__wrapper):hover {
  border-color: #c0c4cc;
}

.search-input :deep(.el-input__wrapper.is-focus) {
  border-color: #409eff;
  background-color: #fff;
}

.service-list {
  min-height: 400px;
}

.service-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: #fff;
  border: 1px solid #f0f0f0;
  border-radius: 12px;
  margin-bottom: 12px;
  transition: all 0.3s ease;
  cursor: pointer;
}

.service-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 12px rgba(64, 158, 255, 0.1);
  transform: translateY(-1px);
}

.service-item:last-child {
  margin-bottom: 0;
}

.service-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.service-avatar {
  margin-right: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.service-details {
  flex: 1;
}

.service-nickname {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  line-height: 1.4;
}

.service-meta {
  margin: 0;
  font-size: 13px;
  color: #909399;
  line-height: 1.4;
}

.service-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.action-button {
  border-radius: 6px;
  font-size: 13px;
  padding: 6px 12px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.action-button:hover {
  transform: translateY(-1px);
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 8px;
}

.pagination-info {
  font-size: 14px;
  color: #606266;
}

.pagination-container :deep(.el-pagination) {
  --el-pagination-button-width: 32px;
  --el-pagination-button-height: 32px;
}

.pagination-container :deep(.el-pagination .btn-next),
.pagination-container :deep(.el-pagination .btn-prev) {
  border-radius: 6px;
}

.pagination-container :deep(.el-pagination .el-pager li) {
  border-radius: 6px;
  margin: 0 4px;
}

.avatar-uploader {
  display: flex;
  justify-content: center;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
  text-align: center;
}

.avatar-upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.upload-actions {
  margin-top: 10px;
  display: flex;
  gap: 10px;
}

.link-container {
  padding: 20px 0;
}

.link-actions {
  margin: 20px 0;
  text-align: center;
}

.link-result {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.link-tips {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}

.link-input {
  width: 100%;
  margin-bottom: 15px;
}

.qr-code-container {
  margin-top: 15px;
  text-align: center;
}

.qr-code {
  margin-top: 10px;
}

.qr-code img {
  width: 150px;
  height: 150px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .customer-service-container {
    padding: 10px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .header-title {
    font-size: 16px;
    text-align: center;
  }
  
  .add-button {
    width: 100%;
    justify-content: center;
  }
  
  .service-item {
    flex-direction: column;
    align-items: flex-start;
    padding: 16px;
    margin-bottom: 16px;
  }
  
  .service-info {
    width: 100%;
    margin-bottom: 16px;
  }
  
  .service-details {
    margin-left: 0;
    margin-top: 12px;
  }
  
  .service-nickname {
    font-size: 15px;
  }
  
  .service-meta {
    font-size: 12px;
    margin-bottom: 8px;
  }
  
  .auto-reply-switch {
    margin-bottom: 8px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  
  .switch-label {
    font-size: 13px;
    margin-right: 8px;
  }
  
  .service-actions {
    margin-top: 12px;
    width: 100%;
    justify-content: flex-start;
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .service-actions .el-button {
    margin: 0;
    font-size: 12px;
    padding: 4px 8px;
  }
  
  .pagination-container {
    flex-direction: column;
    gap: 12px;
    align-items: center;
  }
  
  .pagination-info {
    order: 2;
  }
  
  .search-input {
    width: 100%;
  }
  
  /* 对话框在移动端的优化 */
  .welcome-dialog :deep(.el-dialog) {
    width: 95% !important;
    margin: 0 auto;
    max-height: 90vh;
  }
  
  .welcome-dialog :deep(.el-dialog__body) {
    padding: 15px;
  }
  
  /* 下拉菜单优化 */
  .el-dropdown-menu {
    min-width: 140px;
  }
  
  .el-dropdown-menu__item {
    font-size: 13px;
    padding: 8px 12px;
  }
}

/* 超小屏幕优化 */
@media (max-width: 480px) {
  .customer-service-container {
    padding: 8px;
  }
  
  .service-item {
    padding: 12px;
  }
  
  .service-avatar {
    width: 40px !important;
    height: 40px !important;
  }
  
  .service-nickname {
    font-size: 14px;
  }
  
  .service-meta {
    font-size: 11px;
  }
  
  .auto-reply-switch {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .switch-label {
    font-size: 12px;
  }
  
  .service-actions {
    gap: 6px;
  }
  
  .service-actions .el-button {
    font-size: 11px;
    padding: 3px 6px;
  }
}

/* 欢迎语弹框样式 */
.welcome-dialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
  border-radius: 8px 8px 0 0;
  padding: 20px;
}

.welcome-dialog :deep(.el-dialog__title) {
  color: #303133;
  font-weight: 600;
}

.welcome-dialog :deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

.welcome-dialog :deep(.el-textarea .el-textarea__inner) {
  border-radius: 8px;
  border: 2px solid #e4e7ed;
  transition: all 0.3s ease;
}

.welcome-dialog :deep(.el-textarea .el-textarea__inner):focus {
  border-color: #ffa726;
  box-shadow: 0 0 0 3px rgba(255, 167, 38, 0.1);
}

.welcome-dialog :deep(.el-switch.is-checked .el-switch__core) {
  background-color: #ffa726;
}

.welcome-dialog :deep(.el-input.is-disabled .el-input__wrapper) {
  background-color: #f8f9fa;
  border-color: #e4e7ed;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.dialog-footer .el-button {
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 500;
}

/* 关键词回复弹框样式 */
.keyword-dialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
  border-radius: 8px 8px 0 0;
  padding: 20px;
}

.keyword-dialog :deep(.el-dialog__title) {
  color: #303133;
  font-weight: 600;
}

.keyword-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.service-info-header {
  display: flex;
  align-items: center;
}

.service-name {
  margin-left: 10px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.keyword-content {
  margin-top: 20px;
}

.keyword-empty {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

.keyword-empty :deep(.el-empty__description) {
  margin-top: 20px;
}

.keyword-empty :deep(.el-empty__description button) {
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 500;
}

.keyword-empty :deep(.el-empty__description button:hover) {
  background-color: #409eff;
  color: #fff;
}

.image-upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.image-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
  text-align: center;
}

.image-uploader {
  display: flex;
  justify-content: center;
}

.image-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 120px;
  height: 120px;
}

.image-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
  line-height: 120px;
}

.uploaded-image {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  object-fit: cover;
}

.image-preview {
  position: relative;
  width: 120px;
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-preview:hover .image-overlay {
  opacity: 1;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 120px;
  height: 120px;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
  margin-bottom: 8px;
}

.upload-text {
  font-size: 12px;
  color: #909399;
}

.text-content {
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding: 8px 0;
}

.image-content {
  padding: 8px 0;
}

/* 自动回复开关样式 */
.auto-reply-switch {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.switch-label {
  font-size: 13px;
  color: #606266;
  font-weight: 500;
}

.auto-reply-switch :deep(.el-switch) {
  --el-switch-on-color: #67c23a;
}

.auto-reply-switch :deep(.el-switch__label) {
  font-size: 12px;
  color: #606266;
}

/* 关键词表格样式 */
.keyword-content :deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

.keyword-content :deep(.el-table__header) {
  background-color: #f8f9fa;
}

.keyword-content :deep(.el-table th) {
  background-color: #f8f9fa;
  color: #606266;
  font-weight: 600;
}

.keyword-content :deep(.el-table td) {
  padding: 12px 0;
}

.keyword-content :deep(.el-tag) {
  border-radius: 4px;
  font-size: 12px;
}

/* 关键词表单弹框样式 */
.keyword-form-dialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
  border-radius: 8px 8px 0 0;
  padding: 20px;
}

.keyword-form-dialog :deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

.keyword-form-dialog :deep(.el-input) {
  border-radius: 6px;
}

.keyword-form-dialog :deep(.el-textarea .el-textarea__inner) {
  border-radius: 6px;
  border: 2px solid #e4e7ed;
  transition: all 0.3s ease;
}

.keyword-form-dialog :deep(.el-textarea .el-textarea__inner):focus {
  border-color: #409eff;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.1);
}

/* 自动回复弹框样式 */
.auto-reply-dialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
  border-radius: 8px 8px 0 0;
  padding: 20px;
}

.auto-reply-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.auto-reply-content {
  margin-top: 20px;
}

.auto-reply-empty {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

.auto-reply-empty :deep(.el-empty__description) {
  margin-top: 20px;
}

.auto-reply-empty :deep(.el-empty__description button) {
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 500;
}

.auto-reply-empty :deep(.el-empty__description button:hover) {
  background-color: #409eff;
  color: #fff;
}

/* 自动回复表单弹框样式 */
.auto-reply-form-dialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
  border-radius: 8px 8px 0 0;
  padding: 20px;
}

.auto-reply-form-dialog :deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

.auto-reply-form-dialog :deep(.el-input) {
  border-radius: 6px;
}

.auto-reply-form-dialog :deep(.el-textarea .el-textarea__inner) {
  border-radius: 6px;
  border: 2px solid #e4e7ed;
  transition: all 0.3s ease;
}

.auto-reply-form-dialog :deep(.el-textarea .el-textarea__inner):focus {
  border-color: #409eff;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.1);
}

/* 公众号二维码弹框样式 */
.qrcode-container {
  padding: 20px;
  text-align: center;
}

.qrcode-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 200px;
  color: #909399;
}

.qrcode-loading .el-icon {
  font-size: 32px;
  margin-bottom: 16px;
}

.qrcode-loading p {
  margin: 0;
  font-size: 14px;
}

.qrcode-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 250px;
}

.qrcode-image {
  margin-bottom: 20px;
  padding: 10px;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.qrcode-image img {
  width: 200px;
  height: 200px;
  display: block;
}

.qrcode-tips {
  text-align: center;
  color: #606266;
}

.qrcode-tips .el-icon {
  font-size: 20px;
  color: #409eff;
  margin-bottom: 8px;
}

.qrcode-tips p {
  margin: 8px 0;
  font-size: 14px;
  line-height: 1.5;
}

.qrcode-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 200px;
  color: #f56c6c;
}

.qrcode-error .el-icon {
  font-size: 32px;
  margin-bottom: 16px;
}

.qrcode-error p {
  margin: 0;
  font-size: 14px;
}

.refresh-tip {
  font-size: 12px;
  color: #909399 !important;
  margin-top: 10px;
  font-style: italic;
}

.search-tip {
  margin-left: 15px;
  color: red;
  white-space: nowrap; /* 一行显示，超出不换行 */
}
</style>